package com.googlecode.restitory.gae.hook;

import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeJavaObject;

import com.googlecode.mycontainer.commons.rhino.DefaultRhinoBoxBuilder;
import com.googlecode.mycontainer.commons.rhino.RhinoBox;
import com.googlecode.restitory.gae.Request;
import com.googlecode.restitory.gae.Response;
import com.googlecode.restitory.gae.Type;

public class RhinoHook implements Hook {

	@Override
	public Response execute(Request request, Chain chain) {
		Response resp = chain.copy().execute(new Request(Type.GET, "/hook.js"));
		if (resp.getCode() != 200) {
			return chain.execute(request);
		}

		String hookjs = resp.getContent().toString();

		RhinoBox box = DefaultRhinoBoxBuilder.getBox();
		box.enter();
		try {
			Function f = (Function) box.eval(hookjs, "hook.js");
			NativeJavaObject nat = (NativeJavaObject) box.invoke(getClass(), f,
					request, chain);
			if (nat == null) {
				return null;
			}
			return (Response) nat.unwrap();
		} finally {
			box.exit();
		}
	}

}
